<script lang="ts" setup>
  import { useRouter } from 'vue-router';
  import dayjs from 'dayjs';
  import { Message, Modal } from '@arco-design/web-vue';
  import { ref, onMounted } from 'vue';
  import useTable from '@/hooks/table';
  import { Game, GameSearchParams } from '@/types/game';
  import {
    publishGame,
    deleteGame,
    getGameList,
    notifySignGame,
  } from '@/api/game';
  import GameCard from '@/components/game-card/index.vue';
  import {
    GameRegionLevels,
    GameTypes,
    GameGroupTypes,
    GameStates,
  } from '@/config/game';
  import ProvinceJSON from '@/config/province.json';
  import CityJSON from '@/config/city.json';
  import CreatorTypeSelector from '@/views/game/list/creator-type-selector.vue';
  import SearchForm from './search-form.vue';

  const router = useRouter();

  const { pager, loading, total, list } = useTable<Game>();

  const defaultParams = ref<GameSearchParams>({
    approveStates: [1],
  });
  const searchParams = ref<GameSearchParams>({});

  const getData = async () => {
    loading.value = true;
    try {
      const res = await getGameList({
        ...pager.value,
        ...searchParams.value,
        ...defaultParams.value,
      });
      total.value = res?.data?.data?.total || 0;
      list.value = res?.data?.data?.list || [];
    } finally {
      loading.value = false;
    }
  };

  const handleSearch = (params: GameSearchParams) => {
    pager.value.pageIndex = 1;
    searchParams.value = params;
    getData();
  };

  const handlePageIndexChanged = (pageIndex: number) => {
    pager.value.pageIndex = pageIndex;
    getData();
  };

  onMounted(() => {
    getData();
  });

  const handleMenuClicked = async (game: Game, action: string) => {
    switch (action) {
      case 'DETAIL': {
        const routeInfo = router.resolve({
          name: 'GameDetailApp',
          query: {
            id: game.id,
          },
        });
        window.open(routeInfo.href);
        break;
      }
      case 'SCORE': {
        window.open(`https://www.qmx-golf.com/game/score?gameId=${game.id}`);
        break;
      }
      case 'SCORE_DETAIL': {
        window.open(
          `https://www.qmx-golf.com/game/score-detail?gameId=${game.id}`
        );
        break;
      }
      case 'EDIT': {
        router.push({
          name: 'GameEditorApp',
          query: {
            id: game.id,
            gameType:
              // eslint-disable-next-line no-nested-ternary
              game.childGameCount === 2
                ? 'stage'
                : game.gameType === 1
                ? 'parent'
                : 'normal',
          },
        });
        break;
      }
      case 'NOTIFY': {
        Modal.confirm({
          title: '确认发送？',
          content: '预报名的用户只能收到一次通知，请谨慎操作！',
          async onBeforeOk() {
            Message.success('通知已开始下发');
            await notifySignGame(game.id);
          },
        });
        break;
      }
      case 'ARRAIGN': {
        await publishGame(game.id);
        getData();
        Message.success('已提交审核');
        break;
      }
      case 'DELETE': {
        Modal.confirm({
          title: '确定删除该赛事？',
          content: '删除后无法恢复',
          onOk: async () => {
            await deleteGame(game.id);
            Message.success('已删除');
            getData();
          },
        });
        break;
      }
      default: {
        break;
      }
    }
  };

  const showCreatorSelector = ref(false);
</script>

<template>
  <div style="padding: 20px">
    <a-row :gutter="[20, 20]">
      <a-col>
        <a-card title="全部赛事" :bordered="false">
          <template #extra>
            <a-button type="primary" @click="showCreatorSelector = true">
              <template #icon><icon-plus /></template>
              新建赛事
            </a-button>
          </template>

          <SearchForm @submit="handleSearch" />
        </a-card>
      </a-col>

      <a-col>
        <a-card :bordered="false">
          <a-table
            :bordered="{ cell: true }"
            :data="list"
            :loading="loading"
            :pagination="{
              total,
              current: pager.pageIndex,
              pageSize: pager.pageSize,
              showTotal: true,
              showJumper: true,
            }"
            @page-change="handlePageIndexChanged"
          >
            <template #columns>
              <a-table-column
                title="赛事"
                data-index="name"
                fixed="left"
                :width="300"
              >
                <template #cell="{ record }">
                  <GameCard :game-info="record" />
                </template>
              </a-table-column>
              <a-table-column title="级别" data-index="phone" :width="100">
                <template #cell="{ record }">
                  {{
                    GameRegionLevels.find((i) => i.value === record.regionLevel)
                      ?.label
                  }}
                </template>
              </a-table-column>
              <a-table-column title="类型" data-index="phone" :width="100">
                <template #cell="{ record }">
                  {{ GameTypes.find((i) => i.value === record.type)?.label }}
                </template>
              </a-table-column>
              <a-table-column title="方式" data-index="phone" :width="100">
                <template #cell="{ record }">
                  {{
                    GameGroupTypes.filter(
                      (i) => (i.value & record.groupType) === i.value
                    )
                      .map((i) => i.label)
                      .join('，')
                  }}
                </template>
              </a-table-column>
              <a-table-column
                title="进程"
                align="center"
                data-index="state"
                :width="120"
              >
                <template #cell="{ record }">
                  <!-- 0：报名未开始；1：报名中；2：报名截止但是未开赛；3：比赛中；4：比赛已结束 -->
                  <a-tag
                    :color="
                      ['gray', 'blue', 'blue', 'green', 'orange'][record.state]
                    "
                  >
                    {{
                      GameStates.find((i) => i.value === record.state)?.label
                    }}
                  </a-tag>
                </template>
              </a-table-column>
              <a-table-column title="地区" data-index="phone" :width="200">
                <template #cell="{ record }">
                  <span v-if="record.gameType === 0 || record.gameType === 2">
                    {{
                      ProvinceJSON.find((i) => i.id === record.province)?.name
                    }}/{{
                      CityJSON[record.province as keyof typeof CityJSON].find(
                        (i) => i.id === record.city
                      )?.name
                    }}
                  </span>
                  <span v-else>-</span>
                </template>
              </a-table-column>
              <a-table-column
                title="创建时间"
                data-index="gmtCreate"
                :width="200"
              >
                <template #cell="{ record }">
                  {{ dayjs(record.gmtCreate).format('YYYY/MM/DD HH:mm:ss') }}
                </template>
              </a-table-column>
              <a-table-column
                title="操作"
                align="center"
                :width="120"
                fixed="right"
              >
                <template #cell="{ record }">
                  <a-dropdown
                    @select="handleMenuClicked(record, $event as string)"
                  >
                    <a-link> 操作 </a-link>
                    <template #content>
                      <a-doption value="DETAIL">查看详情</a-doption>
                      <a-doption value="SCORE_DETAIL">查看成绩</a-doption>
                      <a-doption value="EDIT"> 编辑 </a-doption>
                      <a-doption v-if="record.gameType === 1" value="NOTIFY">
                        发送报名通知
                      </a-doption>
                      <a-doption
                        :disabled="
                          record.state !== -1 || record.createFrom === 2
                        "
                        value="DELETE"
                      >
                        删除
                      </a-doption>
                    </template>
                  </a-dropdown>
                </template>
              </a-table-column>
            </template>
          </a-table>
        </a-card>
      </a-col>
    </a-row>

    <CreatorTypeSelector
      v-if="showCreatorSelector"
      @close="showCreatorSelector = false"
    />
  </div>
</template>
